<script setup lang="ts">
import AddScreening from '@/components/AddScreening.vue'
import UserInformation from '@/components/UserInformation.vue'
import { showConfirmDialog, showFailToast } from 'vant'
// @ts-ignore
import { cookieUtil } from '@/utils/cookie'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { getUserWechatAccounts } from '@/api/wechat/app'
import { getCheckers } from '@/api/wechat/user'
import ScreeningItem from '@/components/ScreeningItem.vue'
import type { CheckPerson } from '@/api/types'

const router = useRouter()
const userInfo = ref<{ nickname: string }>({
  nickname: '',
})
const checkPersonList = ref<CheckPerson[]>([])

// 根据openid去获取用户信息 渲染
const user_open_id = cookieUtil.get('open_id')
const user_avator = cookieUtil.get('user_avator')

getCheckers().then((res: any) => {
  checkPersonList.value = res.data
})

getUserWechatAccounts(user_open_id)
  .then((res: any) => {
    if (res.code == 200) {
      if (res.data.tel == null || res.data.userName == null) {
        // 如果没有绑定微信
        router.push('/login/before')
      } else {
        userInfo.value = res.data
      }
    }
  })
  .catch((err) => {
    showFailToast('获取用户信息失败' + err)
    router.push('/login/before')
  })

// 退出登录的逻辑 清除Cookie所有的值 重定向到登录页面
function logout() {
  showConfirmDialog({
    title: '登出',
    message: '您是否要退出登录?',
  })
    .then(() => {
      handleLogout().then(() => {
        window.location.reload()
      })
    })
    .catch(() => {})
}

// 清除所有的本地存储
function handleLogout() {
  return new Promise<void>((resolve, reject) => {
    cookieUtil.remove('user_token')
    cookieUtil.remove('code')
    cookieUtil.remove('open_id')
    cookieUtil.remove('user_nickname')
    cookieUtil.remove('user_avator')
    sessionStorage.removeItem('open_id')
    resolve()
  })
}
</script>

<template>
  <div>
    <div class="home-container">
      <div class="home-user-body">
        <user-information :username="userInfo.nickname" :avator="user_avator">
          <template #option>
            <span class="user-logout" @click="logout">退出</span>
          </template>
        </user-information>
        <!-- 筛查人需要点击筛查后动态添加 -->
        <div v-for="(item, index) in checkPersonList" :key="index">
          <screening-item :check-person-info="item" />
        </div>
        <!--        点击添加后可以添加筛查人-->
        <add-screening />
      </div>
    </div>
  </div>
</template>

<style scoped>
.home-container {
  width: 100%;
  height: 800px;
  background-image: url(../../src/assets/bg.png);
  background-position: center 0;
  background-size: contain;
  background-repeat: no-repeat;
}

.home-user-body {
  padding-top: 17rem;
}

.user-logout {
  cursor: pointer;
  font-size: 1rem;
  font-weight: 700;
  color: #4c4c4c;
}
</style>
